<?php

class Request_User_Data_API_Endpoint {

    public function __construct() {
        add_filter('query_vars', array($this, 'add_query_vars'), 0);
        add_action('parse_request', array($this, 'sniff_requests'), 0);
        add_action('init', array($this, 'add_endpoint'), 0);
    }

    /** Add public query vars
     * 	@param array $vars List of current public query vars
     * 	@return array $vars 
     */
    public function add_query_vars($vars) {
        $vars[] = '__api';
        $vars[] = 'action';
        return $vars;
    }

    /** Add API Endpoint
     * 	This is where the magic happens - brush up on your regex skillz
     * 	@return void
     */
    public function add_endpoint() {
        add_rewrite_rule('^api/request_user_data/?', 'index.php?__api=1&action=fe_request_user_data', 'top');
    }

    /** 	Sniff Requests
     * 	This is where we hijack all API requests
     * 	If $_GET['__api'] is set, we kill WP and serve up pug bomb awesomeness
     * 	@return die if API request
     */
    public function sniff_requests() {
        global $wp;

        if (isset($wp->query_vars['action']) && $wp->query_vars['action'] == "fe_request_user_data") {
            $this->handle_request();
            exit;
        }
    }

    /** Handle Requests
     * 	This is where we send off for an intense pug bomb package
     * 	@return void 
     */
    protected function handle_request() {

        global $wp, $wpdb;

        if (!is_user_logged_in()) {
            $this->send_response('Error');
        }
        
        $user = wp_get_current_user();
        $user_id = $user->ID;

        $functions = array('getWorkersMonths', 'getWorkersNumber', 'getSectorMonths', 'getSectors', 'getSubSectors', 'getTodoSubSectors' ,'getProductMonths','getProduct');

        if (isset($_POST) && in_array($_POST['func'], $functions)) {

            if ($_POST['func'] == 'getWorkersMonths') {
                
                $year = $_POST['year'];
                $months = $wpdb->get_col($wpdb->prepare("select distinct month from bpa_registry_workers where user_id = %d and year = %d order by month asc", $user_id, $year));
                
                $data = "";
                $month_actual = date('n');
                foreach ($months as $month) {
                    $month_label = get_year_from_index($month);
                    $selected = ($month==$month_actual?" selected ":"");                    
                    $data .= '<option value="'.$month.'" '.$selected.'>'.$month_label.'</option>';                    
                }

                $this->send_response('OK', $data);
                
            } else if ($_POST['func'] == 'getWorkersNumber') {
                
                $year = $_POST['year'];
                $month = $_POST['month'];
                $data = $wpdb->get_var($wpdb->prepare("select number from bpa_registry_workers where user_id = %d and year = %d and month = %d", $user_id, $year, $month));
                $this->send_response('OK', $data);
                
            } else if ($_POST['func'] == 'getSectorMonths') {
                
                $year = $_POST['year'];
                $months = $wpdb->get_col($wpdb->prepare("select distinct month from bpa_registry_sector where user_id = %d and year = %d order by month asc", $user_id, $year));
                
                $data = "";
                $month_actual = date('n');
                foreach ($months as $month) {
                    $month_label = get_year_from_index($month);
                    $selected = ($month==$month_actual?" selected ":"");                    
                    $data .= '<option value="'.$month.'" '.$selected.'>'.$month_label.'</option>';                    
                }

                $this->send_response('OK', $data);
                
            } else if ($_POST['func'] == 'getSectors') {
                $year = $_POST['year'];
                $month = $_POST['month'];
                $current_sector_id = $wpdb->get_var($wpdb->prepare("select sector_id from bpa_registry_sector where user_id = %d and year = %d and month = %d", $user_id,$year,$month));
                $sectors = $wpdb->get_results($wpdb->prepare("select * from bpa_company_sector",""));
                
                $data = "";
                foreach ($sectors as $sector) {
                    $selected = ($sector->id == $current_sector_id ? "selected " : "");
                    $data .= '<option value="'.$sector->id.'" '.$selected.'>'.$sector->name.'</option>';
                }

                $this->send_response('OK', $data);
                
            } else if ($_POST['func'] == 'getTodoSubSectors') {
                
                $sector = $_POST['sector'];
                $subsectors = $wpdb->get_results($wpdb->prepare("select * from bpa_company_subsector where sector_id = %d order by name asc", $sector));
                
                $data = "";
                $selected = " selected ";
                foreach ($subsectors as $subsector) {
                    $data .= '<option value="'.$subsector->id.'" '.$selected.'>'.$subsector->name.'</option>';
                    $selected = "";                    
                }

                $this->send_response('OK', $data);
                
            }else if ($_POST['func'] == 'getSubSectors') {
                
                $sector = $_POST['sector'];
                $year = $_POST['year'];
                $month = $_POST['month'];
                $current_subsector_id = $wpdb->get_var($wpdb->prepare("select subsector_id from bpa_registry_sector where user_id = %d and year = %d and month = %d", $user_id,$year,$month));
                $subsectors = $wpdb->get_results($wpdb->prepare("select * from bpa_company_subsector where sector_id = %d order by name asc", $sector));
                
                $data = "";
                foreach ($subsectors as $subsector) {
                    $selected = $subsector->id == $current_subsector_id ? "selected" : "";
                    $data .= '<option value="'.$subsector->id.'" '.$selected.'>'.$subsector->name.'</option>';
                }

                $this->send_response('OK', $data);
                
            } else if ($_POST['func'] == 'getProduct') {
                
                $year = $_POST['year'];
                $month = $_POST['month'];
                $data = $wpdb->get_var($wpdb->prepare("select product from bpa_registry_product where user_id = %d and year = %d and month = %d", $user_id, $year, $month));
                $this->send_response('OK', $data);
                
            }else if ($_POST['func'] == 'getProductMonths') {
                
                $year = $_POST['year'];
                $months = $wpdb->get_col($wpdb->prepare("select distinct month from bpa_registry_product where user_id = %d and year = %d order by month asc", $user_id, $year));
                
                $data = "";                
                $month_actual = date('n');
                foreach ($months as $month) {
                    $month_label = get_year_from_index($month);
                    $selected = ($month==$month_actual?" selected ":"");                    
                    $data .= '<option value="'.$month.'" '.$selected.'>'.$month_label.'</option>';                    
                }

                $this->send_response('OK', $data);
                
            } else {
               $this->send_response('Error'); 
            }

        } else {
            $this->send_response('Error');
        }
    }

    /** Response Handler
     * 	This sends a JSON response to the browser
     */
    protected function send_response($msg, $data = '') {
        $response['status'] = $msg;
        if ($data)
            $response['content'] = $data;
        header('content-type: application/json; charset=utf-8');
        echo json_encode($response) . "\n";
        exit;
    }

}

new Request_User_Data_API_Endpoint();

?>
